# Copyright (c) 2020 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""EII Message Bus subscriber example
"""

import eii.msgbus as mb
import os
import json
from distutils.util import strtobool
import cfgmgr.config_manager as cfg
from util.util import Util
import socket


def start_subscriber():

    # Read config
    ctx = cfg.ConfigMgr()
    json_config = ctx.get_app_config()
    tcp_server_ip = json_config["tcp_server_ip"]
    tcp_server_port = int(json_config["tcp_server_port"])

    if not tcp_server_ip or not tcp_server_port:
        print("Invalid tcp server ip or port")
        return
   
    # Init Socket
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcp_server_socket.bind((tcp_server_ip, tcp_server_port))
    tcp_server_socket.listen(300)
    print("Waiting connect...")
    service_client_socket, ip_port = tcp_server_socket.accept()
    print("one connect")
 
    try:
        num_of_subscribers = ctx.get_num_subscribers()
        if num_of_subscribers < 1:
            raise "No subscriber instances found, exiting..."
        sub_ctx = ctx.get_subscriber_by_index(0)
        msgbus_cfg = sub_ctx.get_msgbus_config()
        topic = sub_ctx.get_topics()[0]

        print('[INFO] Initializing message bus context')
        msgbus_sub = mb.MsgbusContext(msgbus_cfg)

        print(f'[INFO] Initializing subscriber for topic {topic}')
        subscriber = msgbus_sub.new_subscriber(topic)

        print('[INFO] Running...')

        while True:
            msg, _ = subscriber.recv()
            if msg is not None:
                msg_to_send = json.dumps(msg).encode("utf-8")
                service_client_socket.send(msg_to_send)
                print(f'[INFO] TCP sent : {msg_to_send}')
            else:
                print('[INFO] Receive interrupted')
    
        service_client_socket.close()
        tcp_server_socket.close()
  
    except KeyboardInterrupt:
        print('[INFO] Quitting...')
    finally:
        if subscriber is not None:
            subscriber.close()
